import { getData } from '@vimi/utils-api'
import { addressCut, addressSplit } from '@vimi/utils-tool'
import { SERVICE_NAME } from '@/gov/plugins/constant'
import { provinceGoodsServiceId } from '@/credit/views/province/goods/goodsMixins'
export const getGoodsQueryAddress = address => {
  const queryAddress = addressSplit(address)
  const { length } = queryAddress
  if (length) {
    queryAddress[length - 1] = addressCut(queryAddress[length - 1])
  }
  return queryAddress
}

const state = {
  creditGoods: [],
}

const getters = {
  creditGoods: state => state.creditGoods,
}

const actions = {
  async getCreditGoods({ commit, rootGetters }) {
    // if (!force && state.creditGoods.length) {
    //   return Promise.resolve(state.creditGoods)
    // }

    const params = {
      'is_approval.eq': 1,
      'is_industrial_package.eq': 1,
      'orWhere.supply_address_code.like': getGoodsQueryAddress(rootGetters.user.queryAddressCode),
    }
    if (rootGetters.user.orgRegionLever === 1) {
      params['service_id.eq'] = provinceGoodsServiceId
    } else if (rootGetters.user.orgRegionLever === 2) {
      params['service_id.in'] = `${rootGetters.clientId},${provinceGoodsServiceId}`
      // params.orWhereAndTemplate = 1
      // params['orWhereAnd.service_id.eq'] = rootGetters.clientId
      // params['orWhereAnd.service_id.neq'] = provinceGoodsServiceId

      // params['orWhereAnd.service_id.in'] = provinceGoodsServiceId
      // params['orWhereAnd.is_approval.eq'] = 1
    }

    const res = await getData(SERVICE_NAME, 'industrial_package', params)
    const data = (res && res.data) || []

    commit('creditGoods', data)
    return data
  },
}

const mutations = {
  creditGoods: (state, payload) => (state.creditGoods = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
